/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */

$(function () {
    'use strict';
    org.breezee.customerIds = [];
    org.breezee.page = {
        init: function () {
            let loginAccountId = $("#_loginAccountId").val();
            let loginCustomerId = $("#_loginCustomerId").val();
            let loginVendorId = $("#_loginVendorId").val();
            if((loginVendorId != null && loginVendorId != "")
            || (loginCustomerId != null && loginCustomerId != "")) {
                Dolphin.ajax({
                    url: '/api/c666378c5d3b417d8e150c456a489d23@accountId=' + loginAccountId,
                    type: Dolphin.requestMethod.GET,
                    async: false,
                    onSuccess: function (reData) {
                        $.each(reData.rows, function (index, obj) {
                            org.breezee.customerIds.push(obj.id);
                        });
                    }
                });
            }

            Dolphin.form.parse();
            this.initEvent();
            this._userList = this.userList('#userList');
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            var me = this;
            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function (e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13) {
                    $(".btn-query").click();
                }
            });
            /**
             *
             * 新建帐号
             */
            $(".newAccount").click(function () {
                var loginVendorId = $("#_loginVendorId").val();
                var loginAccountId = $("#_loginAccountId").val();
                Dolphin.form.empty('.edit-form');
                //如果是以客户登录，默认类型是客户，客户只能选择自己
                var customerId = org.breezee.context.userData.customerId || '';
                if (customerId ) {
                    $("#acctType").empty();
                    $("#acctType").append('<option value="2">' + Dolphin.i18n.get("frameworkType.client") + '</option>');
                    $("#acctType").change();

                    // optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                    // optionParam='{"properties":{"category":"1"}}'
                    var condition = '{"properties":{"category":"1","id": "' + customerId + '"}}';


                    $("#customerSelect").attr({"class":"form-control", "options":"", "ajaxType": "post", "codeField":"id", "nameField":"name"});
                    $("#customerSelect").empty().attr("optionUrl", "/api/742445c653654caaa4a1fa69eb651a9a").attr("optionParam", condition);
                    Dolphin.form.parseSelect($(".edit-form").find('#customerSelect'));

                } else if(loginVendorId != null && loginVendorId != ""){
                    $("#acctType").empty();
                    $("#acctType").append('<option value="2">' + Dolphin.i18n.get("frameworkType.client") + '</option>');
                    $("#acctType").change();

                    let _this = $("#customerSelect");
                    _this.empty().attr({"class":"js-example-basic-single", "style":"width:100%"});
                    Dolphin.ajax({
                        url: '/api/c666378c5d3b417d8e150c456a489d23@accountId='+loginAccountId,
                        type: Dolphin.requestMethod.GET,
                        async : false,
                        onSuccess: function (reData) {
                            _this.append(
                                '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                            $.each(reData.rows,function(index,obj){
                                _this.append(
                                    '<option value="' + obj.id + '">'
                                    + obj.name + '</option>');
                            });
                        }
                    });
                    $(".js-example-basic-single").select2();
                } else {
                    $("#acctType").empty();
                    $("#acctType").append('<option value="1">' + Dolphin.i18n.get("frameworkType.admin") + '</option><option value="2">' + Dolphin.i18n.get("frameworkType.client") + '</option><option value="3">' + Dolphin.i18n.get("frameworkType.channelDistributor") + '</option>');

                    var condition = '{"properties":{"category":"1"}}';
                    $("#customerSelect").attr({"class":"form-control", "options":"", "ajaxType": "post", "codeField":"id", "nameField":"name"});
                    $("#customerSelect").empty().attr("optionUrl", "/api/742445c653654caaa4a1fa69eb651a9a").attr("optionParam", condition);
                    Dolphin.form.parseSelect($(".edit-form").find('#customerSelect'));

                }

                $('#account_win').modal('show');
            });

            /**
             * 保存按钮
             */
            $(".btn_submit").click(function () {
                var ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    var data = Dolphin.form.getValue(ef, '"');
                    if (data.type == 1) {
                        delete data['customer'];
                        delete data['vendor'];
                    } else if (data.type == 2) {
                        delete data['vendor'];
                    } else if (data.type == 3) {
                        delete data['customer'];
                    }
                    console.log(data);
                    if(org.breezee.context.userData.accountType == 3 &&
                        (org.breezee.context.userData.vendorId != "" || org.breezee.context.userData.vendorId)){
                        Dolphin.ajax({
                            url: '/api/756af3ae31a64565a54ec0221f84d378',
                            type: Dolphin.requestMethod.PUT,
                            data: Dolphin.json2string(data),
                            onSuccess: function (reData) {
                                me._userList.load();
                                $('#account_win').modal('hide');
                            }
                        });

                    }else{

                        Dolphin.ajax({
                            url: '/api/756af3ae31a64565a54ec0221f84d377',
                            type: Dolphin.requestMethod.PUT,
                            data: Dolphin.json2string(data),
                            onSuccess: function (reData) {
                                me._userList.load();
                                $('#account_win').modal('hide');
                            }
                        });
                    }


                }
            });
            $('.content-refresh').click(function () {
                me._userList.reload();
            });

            $(".btn-query").click(function () {
                me._userList.load('', Dolphin.form.getValue('.query-form'));
            });

            $('.all-btn-lock').click(function () {
                var data = Dolphin.form.getValue('.query-form');
                me.userLock({properties: data, status: 0});
            });

            $('.all-btn-unlock').click(function () {
                var data = Dolphin.form.getValue('.query-form');
                me.userLock({properties: data, status: 1});
            });
            //155d0ad633dc46f98246926c4acceca1
            $('.restPwd').click(function () {
                var items = me._userList.getChecked();
                if (items.length > 0) {
                    Dolphin.confirm(Dolphin.i18n.get("account.resetPassword"), {
                        callback: function (flg) {
                            if (flg) {
                                var pl = [];
                                for (var i = 0; i < items.length; i++) {
                                    pl.push(items[i].id);
                                }
                                Dolphin.ajax({
                                    url: '/api/15f66c54650c443386878f5b818dc48f',
                                    data: Dolphin.json2string({id: pl.join(',')}),
                                    type: Dolphin.requestMethod.POST,
                                    onSuccess: function (reData) {
                                        $(".btn-query").click();
                                    }
                                });
                            }
                        }
                    });
                }
            });

            $("#acctType").change(function () {
                var v = $(this).val();
                $(".cusCate").addClass('hidden');
                if (v == 1) {

                } else if (v == 2) {
                    $(".cusId").removeClass('hidden');
                } else if (v == 3) {
                    $(".chanId").removeClass('hidden');
                }
            });
        },
        userList: function (panelId) {
            let me = this;
            let type = ["", Dolphin.i18n.get("frameworkType.admin"), Dolphin.i18n.get("frameworkType.client"), Dolphin.i18n.get("frameworkType.channelDistributor")];
            let customer_ids_param = {};
            if(org.breezee.context.userData.accountType != 1){
                customer_ids_param = { customer_id_obj_in_ae : (org.breezee.customerIds.length > 0 ? org.breezee.customerIds.join(",") : 'TBD') };
            }

            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                queryParams: customer_ids_param,
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("account.accountName"),
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("account.accountCode")
                }, {
                    code: 'type',
                    title: Dolphin.i18n.get("account.accountType"),
                    width: '130px',
                    formatter: function (val) {
                        return val && type[val];
                    }
                }, {
                    code: 'status',
                    title: Dolphin.i18n.get("account.status"),
                    width: '110px',
                    formatter: function (val) {
                        return val ? Dolphin.i18n.get("equipment.normal") : '<span style="color: red;">' + Dolphin.i18n.get("account.forbiddenedUse") + '</span>';
                    }
                }, {
                    code: 'sex',
                    title: Dolphin.i18n.get("account.gender"),
                    width: '110px',
                    formatter: function (val) {
                        return val == 1 ? Dolphin.i18n.get("account.male") : Dolphin.i18n.get("account.female");
                    }
                }, {
                    code: 'mobile',
                    title: Dolphin.i18n.get("account.cellphoneNumber")
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '200px',
                    formatter: function (val, row, index) {
                        let edit_html;
                        if ($("#accountType").val() != "1") {
                            edit_html = '<a class="btn btn-outline btn-circle btn-sm ban" ><i class="fa fa-edit"></i>' + Dolphin.i18n.get("account.edit") + '</a>';
                        } else {
                            edit_html = '<a class="btn btn-outline btn-circle btn-sm purple editBtn" data-id="' + row.id + '" href="javascript:;">' +
                                '<i class="fa fa-edit"></i>&nbsp;' + Dolphin.i18n.get("account.edit") + '</a>';
                            if(org.breezee.context.userData.userCode == 'admin') {
                                edit_html += '<a class="btn btn-outline btn-circle btn-sm blue tokenBtn" data-p="' + row.password + '" data-u="' + row.code + '" href="javascript:;">' +
                                    '<i class="fa fa-plug"></i>&nbsp;密钥</a>';
                            }
                        }
                        return edit_html
                            + '<a href="javascript:;" data-status="' + Math.abs(row.status - 1) + '" data-id="' + val + '" ' +
                            'class="btn btn-outline btn-circle btn-sm dark lock_btn">' +
                            '<i class="fa fa-' + (row.status > 0 ? 'lock' : 'unlock') + '"></i>' +
                            (row.status > 0 ? Dolphin.i18n.get("account.lockUp") : Dolphin.i18n.get("account.unlock")) + '</a>';
                    }
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/756af3ae31a64565a54ec0221f84d377',
                pagination: true,
                onLoadSuccess: function () {
                    org.breezee.buttons.editCallback('a0f1e5cde2084416946ed6c4c2a25da9', 'id', function (data) {
                        $('#account_win').modal('show');

                        var loginVendorId = $("#_loginVendorId").val();
                        var loginAccountId = $("#_loginAccountId").val();
                        //如果是以客户登录，默认类型是客户，客户只能选择自己
                        var customerId = org.breezee.context.userData.customerId || '';
                        if (customerId ) {
                            $("#acctType").empty();
                            $("#acctType").append('<option value="2">' + Dolphin.i18n.get("frameworkType.client") + '</option>');
                            $("#acctType").val(data.value.type);
                            $("#acctType").change();

                            // optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                            // optionParam='{"properties":{"category":"1"}}'
                            var condition = '{"properties":{"category":"1","id": "' + customerId + '"}}';


                            $("#customerSelect").attr({"class":"form-control", "options":"", "ajaxType": "post", "codeField":"id", "nameField":"name"});
                            $("#customerSelect").empty().attr("optionUrl", "/api/742445c653654caaa4a1fa69eb651a9a").attr("optionParam", condition);
                            Dolphin.form.parseSelect($(".edit-form").find('#customerSelect'));

                        } else if(loginVendorId != null && loginVendorId != ""){
                            $("#acctType").empty();
                            $("#acctType").append('<option value="2">' + Dolphin.i18n.get("frameworkType.client") + '</option>');
                            $("#acctType").val(data.value.type);
                            $("#acctType").change();

                            let _this = $("#customerSelect");
                            _this.empty().attr({"class":"js-example-basic-single", "style":"width:100%"});
                            Dolphin.ajax({
                                url: '/api/c666378c5d3b417d8e150c456a489d23@accountId='+loginAccountId,
                                type: Dolphin.requestMethod.GET,
                                async : false,
                                onSuccess: function (reData) {
                                    _this.append(
                                        '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                                    $.each(reData.rows,function(index,obj){
                                        _this.append(
                                            '<option value="' + obj.id + '">'
                                            + obj.name + '</option>');
                                    });
                                }
                            });
                            $(".js-example-basic-single").select2();
                        } else {
                            $("#acctType").empty();
                            $("#acctType").append('<option value="1">' + Dolphin.i18n.get("frameworkType.admin") + '</option><option value="2">'
                                + Dolphin.i18n.get("frameworkType.client") + '</option><option value="3">'
                                + Dolphin.i18n.get("frameworkType.channelDistributor") + '</option>');
                            $("#acctType").val(data.value.type);
                            $("#acctType").change();
                            var condition = '{"properties":{"category":"1"}}';
                            $("#customerSelect").attr({"class":"form-control", "options":"", "ajaxType": "post", "codeField":"id", "nameField":"name"});
                            $("#customerSelect").empty().attr("optionUrl", "/api/742445c653654caaa4a1fa69eb651a9a").attr("optionParam", condition)
                                .attr("selectedOption",data.value.customerId);
                            Dolphin.form.parseSelect($(".edit-form").find('#customerSelect'));

                        }

                        // var condition = '{"properties":{"category":"1"}}';
                        // $("#customerSelect").attr({"class":"form-control", "options":"", "ajaxType": "post", "codeField":"id", "nameField":"name"});
                        // $("#customerSelect").empty().attr("optionUrl", "/api/742445c653654caaa4a1fa69eb651a9a").attr("optionParam", condition);
                        // Dolphin.form.parseSelect($(".edit-form").find('#customerSelect'));
                    });

                    $('.lock_btn').click(function () {
                        var _this = $(this);
                        me.userLock(_this.data());
                    });

                    $(".tokenBtn").click(function () {
                        let d = $(this).data();
                        Dolphin.ajax({
                            url: '/api/0eaa364576c9486bb1f10073242058d5?usercode=' + d.u + '&password=root',
                            type: Dolphin.requestMethod.GET,
                            onSuccess: function (reData) {
                                alert(reData.token);
                            }
                        });
                    });
                }
            });
        },
        userLock: function (data) {
            var me = this;
            Dolphin.ajax({
                url: '/api/048dc335e64f47b5848493546e7553eb',
                data: Dolphin.json2string(data),
                type: Dolphin.requestMethod.POST,
                onSuccess: function (reData) {
                    $(".btn-query").click();
                }
            });
        }
    };
    org.breezee.page.init();
});